package com.liguo.whoisthespy.ui

import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import club.ddkx.duoduokaixin.adapter.BaseAdapter
import club.ddkx.duoduokaixin.util.ke
import com.google.common.collect.Queues
import com.iflytek.cloud.*
import com.liguo.whoisthespy.R
import com.liguo.whoisthespy.bean.LoadSerializableBean
import com.liguo.whoisthespy.bean.UserBean
import com.liguo.whoisthespy.bean.WordsTbl
import com.liguo.whoisthespy.databinding.ActivityPhaseBinding
import com.liguo.whoisthespy.databinding.ItemPhaseBinding
import com.liguo.whoisthespy.utils.Config
import io.realm.RealmResults
import liguo.util.Util
import liguo.views.BaseActivity
import org.jetbrains.anko.onClick
import org.jetbrains.anko.toast
import java.util.*
import java.util.concurrent.ArrayBlockingQueue

class PhaseActivity : BaseActivity() {
    private val binding by lazy { ActivityPhaseBinding.inflate(layoutInflater) }
    private val adapter by lazy {
        BaseAdapter<UserBean,ItemPhaseBinding>(R.layout.item_phase, (intent.getSerializableExtra(Util.OPTION1) as LoadSerializableBean).listUserBean!!)
    }
    private val lop by lazy { LookOverPpw(this) }//查看词语
    private val wip by lazy { WriteIyricsPpw(this) }//写自定义词语

    private val mTts by lazy { SpeechSynthesizer.createSynthesizer(this){
        if(it != ErrorCode.SUCCESS) Util.showToast("初始化失败")
    } }

    override fun config(savedInstanceState: Bundle?) {
//        setContentView(R.layout.activity_phase)
        setContentView(binding.root)
    }

    override fun initView(savedInstanceState: Bundle?) {
        mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL)
        binding.apply {
            state = 0//0表示选词前（游戏未开始），1表示选词后到描述这一阶段，2表示游戏中
            stateWc = false//true表示点击了忘词
            stateCj = false//true表示点击了出局


            apRecycler.layoutManager = GridLayoutManager(this@PhaseActivity,4)
            apRecycler.adapter = adapter

            adapter.onBind { itemBingding, position, data ->
                itemBingding.root.onClick {
                    if (state==1){
                        //点击头像查看词语
                        showLookOverPpw(data.user.name,data.ciyu)
                        data.check = true
                        adapter.notifyItemChanged(position)
                    }else if(state==2){
                        if(stateWc){
                            //点击头像查看词语
                            stateWc=false
                            showLookOverPpw(data.user.name,data.ciyu)
                        }else if(stateCj){
                            //点击头像出局
                            stateCj=false
                            data.death=true
                            adapter.notifyItemChanged(position)
                            if(data.isSpy){
                                startYuYin("游戏结束，卧底是${data.user.name}")
                                state = 0
                                return@onClick
                            }else{
                                startYuYin("${data.user.name}含冤而死,游戏继续")
                            }
                            val temp = adapter.datas.filter { !it.death }
                            if(temp.count()==3){
                                startYuYin("场上只剩下3个人了，卧底胜利，卧底是${temp.first { it.isSpy }.user.name}")
                            }
                        }
                    }
                }
            }

            apBack.onClick { finish() }
            //快速开始
            apKsks.onClick {
                getCiyu()
            }
            //自定义词语
            apZdycy.onClick {
                showWriteIyricsPpw()
            }
            //开始描述
            apKsms.onClick {
                if(adapter.datas.firstOrNull { !it.check }!=null){
                    toast("还有队员没有查看词语")
                }else{
                    state = 2
                    startYuYin("请${getStartName()}开始你的表演")
                }
            }
            //忘词
            apWc.onClick {
                stateWc=true
            }
            //出局
            apCj.onClick {
                stateCj=true
            }
            //中止游戏
            apZzyx.onClick {
                state = 0
            }
        }
    }

    override fun initData() {
    }

    /**
     * 获取第一个开始人的名字
     */
    fun getStartName()=adapter.datas[Random().nextInt(adapter.datas.size)].user.name

    /**
     * 获取词语
     */
    fun getCiyu(){
        var list: RealmResults<WordsTbl>?=null
        if(Config.isDisableHistory){
            list = realm.where(WordsTbl::class.java).equalTo("played",false).findAll()
            if(list.isEmpty()){
                toast("你已经玩过所有的词了,请去设置里关闭禁用历史词汇")
                return
            }
        }else{
            list = realm.where(WordsTbl::class.java).findAll()
        }
        val w = list[Random().nextInt(list.size)]
        startPlay(w.civilian,w.undercover)
    }

    /**
     * 开始游戏，选择词语
     */
    fun startPlay(civilian:String,undercover:String){
        adapter.datas.forEach {
            it.ciyu = civilian
            it.check=false
            it.death=false
        }
        val index = (Random().nextFloat()*(adapter.datas.lastIndex)).toInt()
        adapter.datas[index].apply {
            ciyu = undercover
            isSpy = true
        }
        binding.apply {
            state=1
            stateCj=false
            stateWc=false
        }
        adapter.notifyDataSetChanged()
        startYuYin("请依次查看自己的词语")
    }


    /**
     * 显示查看词语
     */
    fun showLookOverPpw(name:String,data: String){
        if(lop.isShowing){
            lop.dismiss()
        }else{
            lop.show(binding.apSetting,name,data)
        }
    }

    /**
     * 写自定义词语
     */
    fun showWriteIyricsPpw(){
        if(wip.isShowing){
            wip.dismiss()
        }else{
            wip.show(binding.apSetting)
        }
    }


    private val yuyinQueue = arrayListOf<String>()
    fun startYuYin(s:String){
        yuyinQueue.add(s)
        startYuYin()
    }
    fun startYuYin(){
        if(!mTts.isSpeaking){
            mTts.startSpeaking(yuyinQueue[0],ssl)
        }
    }

    private val ssl = object : SynthesizerListener {
        //缓冲进度回调
        // percent为缓冲进度0~100，beginPos为缓冲音频在文本中开始位置，
        // endPos表示缓冲音频在 文本中结束位置，info为附加信息。
        override fun onBufferProgress(p0: Int, p1: Int, p2: Int, p3: String?) {

        }
        //开始播放
        override fun onSpeakBegin() {
            Util.showToast(yuyinQueue[0])
        }
        //播放进度回调
        // percent为播放进度0~100,beginPos为播放音频在文本中开始位置，
        // endPos表示播放音频在文本中结束位置.
        override fun onSpeakProgress(p0: Int, p1: Int, p2: Int) {
        }
        //会话事件回调接口
        override fun onEvent(p0: Int, p1: Int, p2: Int, p3: Bundle?) {
        }
        //暂停播放
        override fun onSpeakPaused() {
        }
        //恢复播放回调接口
        override fun onSpeakResumed() {
        }
        //会话结束回调接口，没有错误时，error为null
        override fun onCompleted(p0: SpeechError?) {
            yuyinQueue.removeAt(0)
            if (yuyinQueue.isNotEmpty()){
                startYuYin()
            }
        }
    }
}
